﻿// FogBugz Community Case List Plugin
// ----------------------------------
// 
// Copyright 2010, 2011 by Sirius Technologies AG / Arsène von Wyss - avw@gmx.ch
// 
// Development has been sponsered by Sirius Technologies AG, Basel
// 
// Source:
// 
// https://communitycaselist.googlecode.com/hg/
// 
// License:
// 
// The library is distributed under the GNU Lesser General Public License:
// http://www.gnu.org/licenses/lgpl.html
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Text.RegularExpressions;

using FogCreek.FogBugz.Database;
using FogCreek.FogBugz.Plugins;
using FogCreek.FogBugz.Plugins.Api;
using FogCreek.FogBugz.Plugins.Interfaces;

namespace Sirius.CommunityCaseList {
	public partial class CommunityCaseList: Plugin, IPluginPageDisplay, IPluginStaticJS, IPluginStaticCSS, IPluginBugDisplay, IPluginBugCommit {
		public const string PluginID = "communitycaselist@fogbugz.sirius.ch";

		private static readonly Regex ticketParser = new Regex(@"^((?<case>[1-9][0-9]*)|removed(_[1-9][0-9]*)?)_+(?<long>(?<short>(?<char>\S){4,}?)(?<-char>\S)+)(?(char)(?!))$", RegexOptions.CultureInvariant|RegexOptions.ExplicitCapture|RegexOptions.IgnoreCase);

		public static string ExtractShortTicket(string sLongTicket) {
			return ticketParser.Match(sLongTicket).Result("${case}_${short}");
		}

		private static bool IsValidTicket(string sTicket) {
			if (string.IsNullOrEmpty(sTicket)) {
				return false;
			}
			return ticketParser.Match(sTicket).Groups["case"].Success;
		}

		private readonly int fogbugzDatabaseVersion;
		private readonly bool showCasesForAnyCustomerEmail;

		public CommunityCaseList(CPluginApi api): base(api) {
			CSelectQuery versionQuery = api.Database.NewSelectQuery("Version");
			versionQuery.AddSelect("MAX(ixVersion) AS iVersion");
			versionQuery.IgnorePermissions = true;
			fogbugzDatabaseVersion = (int)versionQuery.GetDataSet().Tables[0].Rows[0][0];
			showCasesForAnyCustomerEmail = true;
		}
	}
}
